package com.iot.ic.utils.vertify;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Component
public class AuthInterceptor implements HandlerInterceptor {

	private List<String> list = new ArrayList<String>();
	
	private List<String> matchList=new ArrayList<String>();
	/*@Autowired
	private UserLoginService userLoginService;*/

	public AuthInterceptor() {

		//无需验证请求
		list.add("/upload/");
		list.add("/register");
		list.add("/users/userPhone");
		list.add("devices/\\d.+/records");
		list.add("/users/pwd/forget");
		list.add("/users/authorization");
		matchList.add("/areas/\\d.+/children");
		matchList.add("/v2/api-docs");
		matchList.add("/swagger-resources");
		matchList.add(".*excel.*");
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		/*String method=request.getMethod();
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
		response.addHeader("Access-Control-Max-Age", "3600");
		response.addHeader("Access-Control-Allow-Headers", "x-requested-with,accessToken," +
				"Content-Type"//post方式，contentType为“application/json; charset=utf-8”，需加此参数才能实现跨域访问
		);
		if (method.equals("OPTIONS")){
			return true;
		}
		String path = request.getServletPath();
		String accessToken = request.getHeader("accessToken");
		if (path.contains("/users/changePwdByForget")||path.contains("/pwd"))
			request.setAttribute("accessToken",accessToken);
		if ((list != null && list.contains(path))||(isMatching(path))) {
			return true;//请求通过
		}
		if(accessToken!=null){
			Response<UserLogin> authResponse = userLoginService.authorization(accessToken);
			if (authResponse.getCode()==1) {// token验证成功
				UserLogin userLogin=authResponse.getResult();
				userLoginService.saveOrUpdateLoginAccessToken(userLogin);
				return true;
			}else {
				throw new CustomException(ReturnCode.stateOf(authResponse.getCode()));
			}
		}
		throw new CustomException(ReturnCode.Err_NoTokenFind);*/
		return  true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
						   ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
	
	/**
	 * 判断正则表达式列表中是否存在匹配的
	 * @param path
	 * @return
	 */
	public boolean isMatching(String path){
		for (String match : matchList) {
			if (path.matches(match)) {
				return true;
			}
		}
		return false;
	}

}
